import axios from 'axios'
// import router from '../router'
import { getToken } from '@/utils/auth'
import { jumpToLogin, notifiyError } from '@/utils/public'
import {console} from "vuedraggable/src/util/helper";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  validateStatus: function(status) {
    return status === 200
  },
  timeout: 0// request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // 处理winglinks
    if (config.url.startsWith('/winglinks')) {
      config.baseURL = null
    }
    // 使用mock数据
    if (config.baseURL === 'mock') {
      config.baseURL = process.env.VUE_APP_MOCK_API
    }
    // 不使用token的接口
    if (config.noToken !== 'cms') {
      if (getToken()) {
        config.headers['Authorization'] = 'Bearer ' + getToken()
      }
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 文件相关接口  直接返回response为二进制
    const url = response.config.url
    let unitCodeParams = ''
    if (response.config.url.indexOf('unitCodeParams') !== -1) {
      unitCodeParams = response.config.url.substring(response.config.url.indexOf('unitCodeParams') + 15, response.config.url.indexOf('unitCodeParams') + 17)
    }
    if (url.includes('/dfile/file/download') || url.includes('/repair/excel/download')) {
      return response
    }
    // 应急值班导出
    if (url.includes('/cdaily/emergencyOnDuty/export') || url.includes('/cdaily/emergencyOnDuty/download') ||
      url.includes('/cdaily/emergencyOnDuty/upload')) {
      return response
    }
    // 值班管理导出
    if (url.includes('/cdaily/onDuty/export')) {
      return response
    }
    // 统计分析导出
    if (url.includes('/jcwStat/constructionStatistics/getSkylightImplTimeStatExport') ||
      url.includes('/jcwStat/constructionStatistics/getSkylightImplCountStatExport') ||
      url.includes('/jcwStat/defectStatistics/export')
    ) {
      return response
    }
    // 登录获取token 返回结构与一般接口不同
    if (response.config.url.includes('/auth/oauth/token')) {
      return response
    }
    // 基础网线路基础线路坡度
    if (url.includes(`/jcwBasic${unitCodeParams}/JcLineSlope/download`)) {
      return response
    }
    // 基础网线路基础线路曲线
    if (url.includes(`/jcwBasic${unitCodeParams}/JcLineCurve/download`)) {
      return response
    }
    // 动态分析评价
    if (url.includes(`/jcjcEvalauationSummarys/listAll`)) {
      return response
    }
    // 接触网台账记录导出(6各段不同接口)
    if (url.includes('/jcwRepair/jcwbRepairRecord/exportExcel') || url.includes('/jcwRepairgz/jcwbRepairRecord/exportExcel') ||
      url.includes('/jcwRepairsz/jcwbRepairRecord/exportExcel') || url.includes('/jcwRepaircs/jcwbRepairRecord/exportExcel') ||
      url.includes('/jcwRepairhy/jcwbRepairRecord/exportExcel') || url.includes('/jcwRepairhh/jcwbRepairRecord/exportExcel') ||
      url.includes('/jcwRepairhn/jcwbRepairRecord/exportExcel')) {
      return response
    }
    // 接触网台账记录【设备更换记录】导出(6各段不同接口)
    if (url.includes('/jcwRepair/jcwbRepairRecord/exportDeviceChangeExcel') || url.includes('/jcwRepairgz/jcwbRepairRecord/exportDeviceChangeExcel') ||
      url.includes('/jcwRepairsz/jcwbRepairRecord/exportDeviceChangeExcel') || url.includes('/jcwRepaircs/jcwbRepairRecord/exportDeviceChangeExcel') ||
      url.includes('/jcwRepairhy/jcwbRepairRecord/exportDeviceChangeExcel') || url.includes('/jcwRepairhh/jcwbRepairRecord/exportDeviceChangeExcel') ||
      url.includes('/jcwRepairhn/jcwbRepairRecord/exportDeviceChangeExcel')) {
      return response
    }
    // 接触网统计分析【施工、检修、完成情况】导出(6各段不同接口)
    if (url.includes('/constructionStatistics/dayplanStatExport') || url.includes('/constructionStatistics/skylightImplCountStatExport') ||
      url.includes('/constructionStatistics/skylightImplTimeStatExport') || url.includes('/constructionStatistics/overhaulWorkStatExport') ||
      url.includes('/constructionStatistics/overhaulProgressStatExport') || url.includes('/constructionStatistics/overhaulImplStatExport') ||
      url.includes('/constructionStatistics/defectStatExport')) {
      return response
    }
    if (url.includes('/jcjcEvalauationSummary/listAll')) {
      return response
    }

    const res = response.data
    if (res.status && res.status !== 200) {
      console.error(response.request.responseURL)
      if (res.status === 401) {
        // token失效
        jumpToLogin()
      } else if (res.status === 412) {
        if (res.message === '未查询到当前用户信息') {
          jumpToLogin()
        } else if (res.message === '无效的clientId') {
          notifiyError(res.message)
          setTimeout(function() {
            jumpToLogin()
          }, 1000)
        } else {
          notifiyError(res.message)
        }
      } else {
        console.error(res.message)
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    // 登录获取token   不弹出窗口提示错误   所以提前返回
    if (error.config.url.includes('/auth/oauth/token')) {
      return Promise.reject(error)
    }

    const errorRes = error.response
    if (errorRes) {
      console.error(errorRes.data.message || '服务器错误')
    } else {
      console.error(error.message)
    }
    return Promise.reject(error)
  }
)

export default service
